package com.qf.service;

import com.qf.constant.CacheConstants;
import com.qf.constant.SourceType;
import com.qf.constant.StrategyConstants;
import com.qf.feign.CacheFeign;
import com.qf.model.StandardSubmit;
import com.qf.util.PushMsgUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Map;

/**
 * 责任链管理者, 有策略业务的执行方法
 * @author lixu
 */
@Service
public class FilterChainManagerImpl implements FilterChainManager{


    //过滤器责任链 Key:
    @Autowired
    private Map<String,FilterChainService> filterMap;
    @Autowired
    private CacheFeign cacheFeign;
    @Autowired
    private PushMsgUtil pushMsgUtil;


    /**
     * 执行大量的过滤器
     */
    @Override
    public void executeFilter(StandardSubmit standardSubmit) {

        //1：当前客户ID
        Integer clientID = standardSubmit.getClientID();
        //2：查询缓存
        String key = CacheConstants.CACHE_PREFIX_CLIENT + clientID;
        //"phase,black,limitFiveMinutes,dirtyWords,fee,router"
        String filters = (String) cacheFeign.hget(key, "filters");
        //3:判断
        if(!StringUtils.isEmpty(filters)){
            String[] filterArrays = filters.split(",");
            for (String filter : filterArrays) {
                //责任链中对应的过滤器
                FilterChainService filterChainService = filterMap.get(filter);
                if(filterChainService != null){
                    //执行过滤器
                    boolean strategy = filterChainService.strategy(standardSubmit);
                    //
                    if(!strategy){
                        //过滤器执行失败  需要打印日志及相关操作
                        pushMsgUtil.sendLog(standardSubmit, filter);
                        //过滤器执行失败  给客户发送报告
                        if(SourceType.HTTP == standardSubmit.getSource()){
                            pushMsgUtil.pushReport(standardSubmit, filter);
                        }
                        break;
                    }
                }
                //成功了就继续循环
            }
        }
    }
}
